package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.UserMapper;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.UserAuth;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @Description UserDetailsServiceImpl
 * @Author xxxx
 * @Date 2024-10-29
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 重写校验用户名的方法
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户名查找用户对象UserVo
        UserVo userVo = userMapper.selectByUserName(username);
        //校验用户不能为空，否则抛出异常
        if (ObjectUtil.isEmpty(userVo)){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //校验用户不能停用，否则抛出异常
        if (SuperConstant.DATA_STATE_1.equals(userVo.getDataState())){
            throw new RuntimeException("用户已停用，无法登录");
        }
        //2.返回UserDetails实现类对象
        // 将UserVo转换为UserDetails，注意这里不需要分配角色，因为后面鉴权直接根据用户查询角色与权限即可
        return BeanUtil.toBean(userVo, UserAuth.class);
    }
}
